﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace WPFYanChatServer
{
    internal class ControlServer
    {
        /// <summary>
        /// 服务器端监听器
        /// </summary>
        public static TcpListener ServerListener = null;

        /// <summary>
        /// 保存所有客户端的登陆号码及网络流的哈希表
        /// </summary>
        public static Hashtable userTable = new Hashtable();



        /// <summary>
        /// 关闭监听并释放资源
        /// </summary>
        public void Close()
        {
            if (ServerListener != null)
            {
                ServerListener.Stop();
            }
            //关闭客户端连接并清理资源
            if (userTable.Count != 0)
            {
                foreach (Socket Session in userTable.Values)
                {
                    Session.Shutdown(SocketShutdown.Both);
                }
                userTable.Clear();
                userTable = null;
            }
        }

        /// <summary>
        /// 启动服务器
        /// </summary>
        public void StartServer()
        {



            ServerListener = new TcpListener(IpConfig.getIp(), IpConfig.Port);
            ServerListener.Start();
            while (true)
            {
                TcpClient UserClient = ServerListener.AcceptTcpClient();//创建新用户Socket
                byte[] packetBuff = new byte[64];
                NetworkStream ServerStream = UserClient.GetStream();

                int len = ServerStream.Read(packetBuff, 0, packetBuff.Length);
                //Console.WriteLine("新用户请求连接...");
                string userNumber = Encoding.Default.GetString(packetBuff, 0, len).TrimEnd('\0');
                //将新的连接加入用户表
                if (!userTable.ContainsKey(userNumber.ToString()))
                {
                    userTable.Add(userNumber, UserClient);
                }
                string loginInfo = string.Format("[系统消息]用户{0}登陆服务器...时间:{1}  当前在线人数:{2}\r\n", userNumber, System.DateTime.Now, userTable.Count);
                //Console.WriteLine(loginInfo);
                Thread newClientThread = new Thread(new ParameterizedThreadStart(Transmit.transmitThread));
                newClientThread.Start(userNumber);

            }
        }
    }
}